<?php
/**
 * 春哥团队（www.cgtblog.com） - 春哥多端多商户万能DIY商城系统
 * Copyright © 2024 春哥技术团队 保留所有权利
 * =========================================================

 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

namespace app\custom;
use think\facade\Db;
class OrderCustom
{
    public function deal_first_cashback($aid,$mid,$back_price,$og,$v,$type = 0,$canshtype = 'shop')
    {

        if(getcustom('yx_cashback_time')){
        //  自定义第一次发放
        //  参数为 ：back_price总返回数额 og订单商品 v购物返现设置 type发放类型 0:立即发放（前面已发放过） 1：自定义发放（需要在这发放）canshtype 记录类型

            //再次验证
            if($v['return_type'] == 1){
                //如果天数小于2，则直接发放
                if($v['return_day']<=1){
                    $status   = 2;
                    $ave_num  = $back_price;
                    $send_num = $back_price;

                }else{
                    $status   = 1;

                    //计算平均发放数值
                    $ave_num = $back_price/$v['return_day'];

                    //计算此次发放数值
                    if($v['back_type'] != 3){
                        $send_num = round($ave_num,2);
                    }else{
                        $ave_num  = round($ave_num);
                        if($ave_num<=1){
                            $ave_num = 1;
                        }
                        $send_num = $ave_num;
                    }

                    //处理特殊情况
                    if($send_num>=$back_price){
                        $send_num = $back_price;
                        $status   = 2;
                    }
                }
            }else{
                $status   = 2;
                $ave_num  = $back_price;
                $send_num = $back_price;
            }

            $data = [];
            $data['cashback_id']       = $v['id'];//活动id
            //判定限额
            $cashback_member_check = Db::name('cashback_member')->where('aid',aid)->where('mid',$mid)->where(['cashback_id'=>$v['id'],'pro_id'=>$og['proid']])->find();
            
            if($v['back_type'] == 1 ){
                $data['moneystatus']    = $status;
                $data['allmoney']       = $back_price;//总返回数值
                $data['money']          = $send_num;//已发放的数值
                $data['moneyave']       = $ave_num;//平均每次发放是数值
                $data['moneyday']       = $v['return_day'];;//发放多少天
                
                $data['money_sendtime'] = time();//发放时间
                $data['money_name']     = $v['name'];;//返现名称
                $data['money_sendnum']  = 1;//发放次数

                $where[]= ['moneystatus','=',0];                

                if($type == 1){
                    if($v['goods_multiple_max'] > 0 &&  $cashback_member_check['cashback_money_max'] > $cashback_member_check['cashback_money']){
                        //最大可追加金额
                        $cashback_money_max = $cashback_member_check['cashback_money_max'] - $cashback_member_check['cashback_money'];
                        if($cashback_money_max < $ave_num){
                            $ave_num = $cashback_money_max;
                        }    
                        if($ave_num <=0){
                            return ;
                        }                                                
                        
                    }
                    //需要发放第一次平均值
                    \app\common\Member::addmoney($aid,$mid,$ave_num,$v['name']);
                    //累计到参与人统计表
                    Db::name('cashback_member')->where('id',$cashback_member_check['id'])->inc('cashback_money',$ave_num)->update();
                    //写入发放日志
                    $res_cashback_do_log = self::cashbackMemerDoLog($aid,$mid,$v,$og,$ave_num);
                }
            }
            if($v['back_type'] == 2){
                $data['commissionstatus']    = $status;
                $data['allcommission']       = $back_price;
                $data['commission']          = $send_num;
                $data['commissionave']       = $ave_num;
                $data['commissionday']       = $v['return_day'];
                $data['commission_sendtime'] = time();
                $data['commission_name']     = $v['name'];;//返现名称
                $data['commission_sendnum']  = 1;//发放次数

                if($type == 1){
                    if($v['goods_multiple_max'] > 0 &&  $cashback_member_check['cashback_money_max'] > $cashback_member_check['commission']){
                        //最大可追加金额
                        $cashback_money_max = $cashback_member_check['cashback_money_max'] - $cashback_member_check['commission'];
                        if($cashback_money_max < $ave_num){
                            $ave_num = $cashback_money_max;
                        }    
                        if($ave_num <=0){
                            return ;
                        }                                                
                        
                    }
                    //需要发放第一次平均值
                    \app\common\Member::addcommission($aid,$mid,$mid,$ave_num,$v['name']);
                    //累计到参与人统计表
                    Db::name('cashback_member')->where('id',$cashback_member_check['id'])->inc('commission',$ave_num)->update();
                    //写入发放日志
                    $res_cashback_do_log = self::cashbackMemerDoLog($aid,$mid,$v,$og,$ave_num);
                }
            }
            if($v['back_type'] == 3){
                $data['scorestatus']    = $status;
                $data['allscore']       = $back_price;
                $data['score']          = $send_num;
                $data['scoreave']       = $ave_num;
                $data['scoreday']       = $v['return_day'];
                $data['score_sendtime'] = time();
                $data['score_name']     = $v['name'];;//返现名称
                $data['score_sendnum']  = 1;//发放次数

                if($type == 1){
                    if($v['goods_multiple_max'] > 0 &&  $cashback_member_check['cashback_money_max'] > $cashback_member_check['score']){
                        //最大可追加金额
                        $cashback_money_max = $cashback_member_check['cashback_money_max'] - $cashback_member_check['score'];
                        if($cashback_money_max < $ave_num){
                            $ave_num = $cashback_money_max;
                        }    
                        if($ave_num <=0){
                            return ;
                        }                                                
                        
                    }
                    //需要发放第一次平均值
                    \app\common\Member::addscore($aid,$mid,$ave_num,$v['name']);
                    //累计到参与人统计表
                    Db::name('cashback_member')->where('id',$cashback_member_check['id'])->inc('score',$ave_num)->update();
                    //写入发放日志
                    $res_cashback_do_log = self::cashbackMemerDoLog($aid,$mid,$v,$og,$ave_num);
                }
            }

            if(getcustom('cashback_yongjin')){
                //记录累计返现金额
                Db::name('member')->where('id',$og['mid'])->inc('cashback_total',$send_num)->update();
            }
            //查询是否有此商品返现表
            $goods_cashback = Db::name('shop_order_goods_cashback')->where('mid',$mid)->where('sog_id',$og['id'])->where('pro_id',$og['proid'])->where('back_type',$v['back_type'])->where('canshtype',$canshtype)->field('id')->find();
            if($goods_cashback){
                $data['updatetime'] = time();
                Db::name('shop_order_goods_cashback')->where('id',$goods_cashback['id'])->update($data);
            }else{
                $data['aid']    = $og['aid'];
                $data['bid']    = $og['bid'];
                $data['mid']    = $mid;
                $data['sog_id'] = $og['id'];//订单商品id
                $data['pro_id'] = $og['proid'];//订单商品id
                $data['back_type'] = $v['back_type'];//返回类型 1：余额 2：佣金 3：积分
                $data['canshtype'] = $canshtype;//购物返回类型 如商城 shop
                if(getcustom('cashback_yongjin')){
                    $data['cashback_yongjin'] = $v['cashback_yongjin'];//抵扣返现
                }

                Db::name('shop_order_goods_cashback')->insert($data);
            }
        }
    }

    public function deal_autocashback()
    {
        if(getcustom('yx_cashback_time')){
        // 自定义每天返现
            //读取配置
            $syssetlist = Db::name('admin_set')->where('1=1')->select()->toArray();
            if($syssetlist){
                //今天
                $today = strtotime(date("Y-m-d",time()));
                foreach($syssetlist as $sv){
                    //余额返现
                    self::deal_moneycashback($sv,$today);
                    //佣金返现
                    self::deal_commissioncashback($sv,$today);
                    //积分返现
                    self::deal_scorecashback($sv,$today);
                }
            }
        }
    }

    private static function deal_moneycashback($sv,$today)
    {
        if(getcustom('yx_cashback_time')){
            //余额返现
            $where = [];
            $where[] = ['aid','=',$sv['aid']];
            $where[] = ['back_type','=',1];
            $where[] = ['moneystatus','=',1];
            $where[] = ['money_sendtime','<',$today];
            if(getcustom('cashback_yongjin')){
                $where[] = ['cashback_yongjin','<>',2];
            }
            $moneylist = Db::name('shop_order_goods_cashback')
                ->where($where)
                ->select()
                ->toArray();
            if($moneylist){
                foreach($moneylist as $mv){
                    if($mv['canshtype'] == "shop"){
                        $count = Db::name('shop_order_goods')
                            ->alias('sog')
                            ->join('shop_order so','so.id = sog.orderid')
                            ->where('sog.id',$mv['sog_id'])
                            ->where('sog.aid',$mv['aid'])
                            ->where('sog.status',3)
                            ->where('so.status',3)
                            ->where('so.delete',0)
                            ->count();
                        if(!$count){
                            continue;
                        }
                    }else if($mv['canshtype'] == "collage"){
                        $count = Db::name('collage_order')
                            ->where('id',$mv['sog_id'])
                            ->where('aid',$mv['aid'])
                            ->where('status',3)
                            ->where('delete',0)
                            ->count();
                        if(!$count){
                            continue;
                        }
                    }else{
                        continue;
                    }
                    //总返回数值
                    $allmoney = $mv['allmoney'];
                    //已发放的数值
                    $money    = $mv['money'];
                    //平均每次发放的数值
                    $moneyave = $mv['moneyave'];
                    //返回天数
                    $day      = $mv['moneyday'];
                    //发放次数
                    $sendnum  = $mv['money_sendnum'];

                    $updata = [];
                    if($money>=$allmoney){
                        $updata['moneystatus']    = 2;
                        $updata['money_sendtime'] = time();
                        $send_money = 0;
                    }else{
                        $send_money  = $moneyave;//发放数值
                        $new_sendnum = $sendnum+1;//发放次数
                        $send_all    = $money+$moneyave;//总发放数值

                        if($send_all<$allmoney){
                            //如果发放次数大于等于返回天数，则这次结束，返回剩余全部
                            if($new_sendnum >= $day){
                                $updata['moneystatus']  = 2;
                                $updata['money']        = $send_all;
                                $updata['money_sendnum']= $new_sendnum;

                                $send_money = $allmoney-$money;
                            }else{
                                $updata['moneystatus']  = 1;
                                $updata['money']        = $send_all;
                                $updata['money_sendnum']= $new_sendnum;
                            }
                        }else if($send_all == $allmoney ){
                            $updata['moneystatus']  = 2;
                            $updata['money']        = $send_all;
                            $updata['money_sendnum']= $new_sendnum;
                        }else{
                            //发放剩余数值
                            $updata['moneystatus']   = 2;
                            $updata['money']         = $allmoney;
                            $updata['money_sendnum'] = $new_sendnum;

                            $send_money = $allmoney-$money;
                        }
                    }
                    if($send_money && $send_money>0){
                        $updata['money_sendtime'] = time();
                        if($mv['cashback_id'] >0 && $mv['pro_id'] >0){
                            $cashback_member_check = Db::name('cashback_member')->where('aid',$sv['aid'])->where('mid',$mv['mid'])->where(['cashback_id'=>$mv['cashback_id'],'pro_id'=>$mv['pro_id']])->find();
                            if($cashback_member_check['cashback_money_max'] > $cashback_member_check['score']){
                                //最大可追加金额
                                $cashback_money_max = $cashback_member_check['cashback_money_max'] - $cashback_member_check['score'];
                                if($cashback_money_max < $send_money){
                                    $send_money = $cashback_money_max;
                                }    
                                if($send_money <=0){
                                    return ;
                                } 
                                //累计到参与人统计表
                                Db::name('cashback_member')->where('id',$cashback_member_check['id'])->inc('cashback_money',$send_money)->update();
                                //写入发放日志
                                $cashback = Db::name('cashback')->where('id',$mv['cashback_id'])->order('sort desc')->find();
                                $og['proid'] = $mv['pro_id'];
                                $res_cashback_do_log = self::cashbackMemerDoLog($sv['aid'],$mv['mid'],$cashback,$og,$send_money);                                            
                                
                            }
                        }
                        
                        //发放返现
                        \app\common\Member::addmoney($sv['aid'],$mv['mid'],$send_money,$mv['money_name']);
                    }
                    //更新
                    $updata['updatetime'] = time();
                    $up = Db::name('shop_order_goods_cashback')->where('id',$mv['id'])->update($updata);
                    if(getcustom('cashback_yongjin')){
                        //记录累计返现金额
                        Db::name('member')->where('id',$mv['mid'])->inc('cashback_total',$send_money)->update();
                    }
                }
            }
        }
    }

    private  static function deal_commissioncashback($sv,$today)
    {
        if(getcustom('yx_cashback_time')){
            //佣金返现
            $where = [];
            $where[] = ['aid','=',$sv['aid']];
            $where[] = ['back_type','=',2];
            $where[] = ['commissionstatus','=',1];
            $where[] = ['commission_sendtime','<',$today];
            if(getcustom('cashback_yongjin')){
                $where[] = ['cashback_yongjin','<>',2];
            }
            $commissionlist = Db::name('shop_order_goods_cashback')
                ->where($where)
                ->select()
                ->toArray();
            if($commissionlist){
                foreach($commissionlist as $mv){
                    if($mv['canshtype'] == "shop"){
                        $count = Db::name('shop_order_goods')
                            ->alias('sog')
                            ->join('shop_order so','so.id = sog.orderid')
                            ->where('sog.id',$mv['sog_id'])
                            ->where('sog.aid',$mv['aid'])
                            ->where('sog.status',3)
                            ->where('so.status',3)
                            ->where('so.delete',0)
                            ->count();
                        if(!$count){
                            continue;
                        }
                    }else if($mv['canshtype'] == "collage"){
                        $count = Db::name('collage_order')
                            ->where('id',$mv['sog_id'])
                            ->where('aid',$mv['aid'])
                            ->where('status',3)
                            ->where('delete',0)
                            ->count();
                        if(!$count){
                            continue;
                        }
                    }else{
                        continue;
                    }
                    //总返回数值
                    $allcommission = $mv['allcommission'];
                    //已发放的数值
                    $commission    = $mv['commission'];
                    //平均每次发放的数值
                    $commissionave = $mv['commissionave'];
                    //返回天数
                    $day      = $mv['commissionday'];
                    //发放次数
                    $sendnum  = $mv['commission_sendnum'];

                    $updata = [];
                    if($commission>=$allcommission){
                        $updata['commissionstatus']    = 2;
                        $updata['commission_sendtime'] = time();
                        $send_commission = 0;
                    }else{
                        $send_commission = $commissionave;//发放数值
                        $new_sendnum     = $sendnum+1;//发放次数
                        $send_all        = $commission+$commissionave;//总发放数值

                        if($send_all<$allcommission){
                            //如果发放次数大于等于返回天数，则这次结束，返回剩余全部
                            if($new_sendnum >= $day){
                                $updata['commissionstatus']  = 2;
                                $updata['commission']        = $send_all;
                                $updata['commission_sendnum']= $new_sendnum;

                                $send_commission = $allcommission-$commission;
                            }else{
                                $updata['commissionstatus']  = 1;
                                $updata['commission']        = $send_all;
                                $updata['commission_sendnum']= $new_sendnum;
                            }
                        }else if($send_all == $allcommission ){
                            $updata['commissionstatus']  = 2;
                            $updata['commission']        = $send_all;
                            $updata['commission_sendnum']= $new_sendnum;
                        }else{
                            //发放剩余数值
                            $updata['commissionstatus']   = 2;
                            $updata['commission']         = $allcommission;
                            $updata['commission_sendnum'] = $new_sendnum;

                            $send_commission = $allcommission-$commission;
                        }
                    }
                    if($send_commission && $send_commission>0){
                        $updata['commission_sendtime'] = time();
                        if($mv['cashback_id'] >0 && $mv['pro_id'] >0){
                            $cashback_member_check = Db::name('cashback_member')->where('aid',$sv['aid'])->where('mid',$mv['mid'])->where(['cashback_id'=>$mv['cashback_id'],'pro_id'=>$mv['pro_id']])->find();
                            if($cashback_member_check['cashback_money_max'] > $cashback_member_check['score']){
                                //最大可追加金额
                                $cashback_money_max = $cashback_member_check['cashback_money_max'] - $cashback_member_check['score'];
                                if($cashback_money_max < $send_commission){
                                    $send_commission = $cashback_money_max;
                                }    
                                if($send_commission <=0){
                                    return ;
                                } 
                                //累计到参与人统计表
                                Db::name('cashback_member')->where('id',$cashback_member_check['id'])->inc('commission',$send_commission)->update();
                                //写入发放日志
                                $cashback = Db::name('cashback')->where('id',$mv['cashback_id'])->order('sort desc')->find();
                                $og['proid'] = $mv['pro_id'];
                                $res_cashback_do_log = self::cashbackMemerDoLog($sv['aid'],$mv['mid'],$cashback,$og,$send_commission);                                            
                                
                            }
                        }
                        //发放返现
                        \app\common\Member::addcommission($sv['aid'],$mv['mid'],$mv['mid'],$send_commission,$mv['commission_name']);
                    }
                    //更新
                    $updata['updatetime'] = time();
                    $up = Db::name('shop_order_goods_cashback')->where('id',$mv['id'])->update($updata);
                    if(getcustom('cashback_yongjin')){
                        //记录累计返现金额
                        Db::name('member')->where('id',$mv['mid'])->inc('cashback_total',$send_commission)->update();
                    }
                }
            }
        }
    }

    private static function deal_scorecashback($sv,$today)
    {
        if(getcustom('yx_cashback_time')){
            //积分返现
            $where = [];
            $where[] = ['aid','=',$sv['aid']];
            $where[] = ['back_type','=',3];
            $where[] = ['scorestatus','=',1];
            $where[] = ['score_sendtime','<',$today];
            if(getcustom('cashback_yongjin')){
                $where[] = ['cashback_yongjin','<>',2];
            }
            $scorelist = Db::name('shop_order_goods_cashback')
                ->where($where)
                ->select()
                ->toArray();
            if($scorelist){
                foreach($scorelist as $mv){
                    if($mv['canshtype'] == "shop"){
                        $count = Db::name('shop_order_goods')
                            ->alias('sog')
                            ->join('shop_order so','so.id = sog.orderid')
                            ->where('sog.id',$mv['sog_id'])
                            ->where('sog.aid',$mv['aid'])
                            ->where('sog.status',3)
                            ->where('so.status',3)
                            ->where('so.delete',0)
                            ->count();
                        if(!$count){
                            continue;
                        }
                    }else if($mv['canshtype'] == "collage"){
                        $count = Db::name('collage_order')
                            ->where('id',$mv['sog_id'])
                            ->where('aid',$mv['aid'])
                            ->where('status',3)
                            ->where('delete',0)
                            ->count();
                        if(!$count){
                            continue;
                        }
                    }else{
                        continue;
                    }
                    //总返回数值
                    $allscore = $mv['allscore'];
                    //已发放的数值
                    $score    = $mv['score'];
                    //平均每次发放的数值
                    $scoreave = $mv['scoreave'];
                    //返回天数
                    $day      = $mv['scoreday'];
                    //发放次数
                    $sendnum  = $mv['score_sendnum'];

                    $updata = [];
                    if($score>=$allscore){
                        $updata['scorestatus']    = 2;
                        $updata['score_sendtime'] = time();
                        $send_score = 0;
                    }else{
                        $send_score  = $scoreave;//发放数值
                        $new_sendnum = $sendnum+1;//发放次数
                        $send_all    = $score+$scoreave;//总发放数值
                        if($send_all<$allscore){
                            //如果发放次数大于等于返回天数，则这次结束，返回剩余全部
                            if($new_sendnum >= $day){
                                $updata['scorestatus']  = 2;
                                $updata['score']        = $send_all;
                                $updata['score_sendnum']= $new_sendnum;

                                $send_score = $allscore-$score;
                            }else{
                                $updata['scorestatus']  = 1;
                                $updata['score']        = $send_all;
                                $updata['score_sendnum']= $new_sendnum;
                            }
                        }else if($send_all == $allscore ){
                            $updata['scorestatus']  = 2;
                            $updata['score']        = $send_all;
                            $updata['score_sendnum']= $new_sendnum;
                        }else{
                            //发放剩余数值
                            $updata['scorestatus']   = 2;
                            $updata['score']         = $allscore;
                            $updata['score_sendnum'] = $new_sendnum;

                            $send_score = $allscore-$score;
                        }
                    }
                    if($send_score && $send_score>0){
                        $updata['score_sendtime'] = time();
                        if($mv['cashback_id'] >0 && $mv['pro_id'] >0){
                            $cashback_member_check = Db::name('cashback_member')->where('aid',$sv['aid'])->where('mid',$mv['mid'])->where(['cashback_id'=>$mv['cashback_id'],'pro_id'=>$mv['pro_id']])->find();
                            if($cashback_member_check['cashback_money_max'] > $cashback_member_check['score']){
                                //最大可追加金额
                                $cashback_money_max = $cashback_member_check['cashback_money_max'] - $cashback_member_check['score'];
                                if($cashback_money_max < $send_score){
                                    $send_score = $cashback_money_max;
                                }    
                                if($send_score <=0){
                                    return ;
                                } 
                                //累计到参与人统计表
                                Db::name('cashback_member')->where('id',$cashback_member_check['id'])->inc('score',$send_score)->update();
                                //写入发放日志
                                $cashback = Db::name('cashback')->where('id',$mv['cashback_id'])->order('sort desc')->find();
                                $og['proid'] = $mv['pro_id'];
                                $res_cashback_do_log = self::cashbackMemerDoLog($sv['aid'],$mv['mid'],$cashback,$og,$send_score);                                            
                                
                            }
                        }
                        //发放返现
                        \app\common\Member::addscore($sv['aid'],$mv['mid'],$send_score,$mv['score_name']);
                    }
                    //更新
                    $updata['updatetime'] = time();
                    $up = Db::name('shop_order_goods_cashback')->where('id',$mv['id'])->update($updata);
                    if(getcustom('cashback_yongjin')){
                        //记录累计返现金额
                        Db::name('member')->where('id',$mv['mid'])->inc('cashback_total',$send_score)->update();
                    }
                }
            }
        }
    }

    public static function deal_collagecashback($aid,$order)
    {
        if(getcustom('yx_cashback_collage')){
            //购物返现
            $cashbacklist = Db::name('cashback')
                ->where('aid',$aid)
                ->where('bid',$order['bid'])
                ->where('starttime','<',$order['paytime'])
                ->where('endtime','>',$order['paytime'])
                ->order('sort desc')
                ->select()->toArray();

            //查询购买用户
            $member = Db::name('member')
                ->where('id',$order['mid'])
                //->field('levelid')
                ->find();
            if($member && $cashbacklist){

                $product = Db::name('collage_product')
                    ->where('id',$order['proid'])
                    ->field('id')
                    ->find();

                if($product){
                    
                    foreach($cashbacklist as $v){

                        if($v['fwtype']!=3){
                            //其他类型不适应
                            continue;
                        }

                        if(getcustom('yx_cashback_collage_moneyreturn')){
                            //判断余额支付返还情况
                            if($order['paytypeid'] == 1){
                                if($order['buytype'] == 1){
                                    //单独 若单购余额返设置为关闭
                                    if($v['alone_moneyreturn'] != 1){
                                        continue;
                                    }
                                }else if($order['buytype'] == 2){
                                    //拼团 团长 若拼团余额返还设置为关闭
                                    if(!$v['team_moneyreturn']){
                                        continue;
                                    }
                                }else{
                                    //拼团 团员 若拼团余额返还设置不是全都返还
                                    if($v['team_moneyreturn'] != 1){
                                        continue;
                                    }
                                }
                            }
                        }

                        $gettj = explode(',',$v['gettj']);
                        if(!in_array('-1',$gettj) && !in_array($member['levelid'],$gettj)){ //不是所有人
                            continue;
                        }

                        $collageids = explode(',',$v['collageids']);
                        if(!in_array($product['id'],$collageids)){
                            continue;
                        }

                        //如果返现利率大于0
                        if($v['back_ratio']>0){
                            //计算返现
                            $back_price = $v['back_ratio']*$order['totalprice']/100;

                            //返现类型 1、余额 2、佣金 3、积分
                            if($v['back_type'] == 1 || $v['back_type']== 2){
                                $back_price = round($back_price,2);
                            }

                            if($v['back_type'] == 3){
                                $back_price = round($back_price);
                            }

                            $send_status = 0;//发放状态
                            if(getcustom('yx_cashback_time')){
                                //如果返回类型为每天返回
                                if($v['return_type'] == 1){
                                    $send_status = 1;//发放状态
                                }
                                //构建商品信息
                                $og = [];
                                $og['aid'] = $order['aid'];
                                $og['bid'] = $order['bid'];
                                $og['mid'] = $order['mid'];
                                $og['id']  = $order['id'];
                            }

                            if(!$send_status){
                                if($back_price>0){
                                    if($v['back_type'] == 1 ){
                                        \app\common\Member::addmoney($aid,$order['mid'],$back_price,$v['name']);
                                    }
                                    if($v['back_type'] == 2){
                                        \app\common\Member::addcommission($aid,$order['mid'],$order['mid'],$back_price,$v['name']);
                                    }
                                    if($v['back_type'] == 3){
                                        \app\common\Member::addscore($aid,$order['mid'],$back_price,$v['name']);
                                    }
                                    if(getcustom('yx_cashback_time')){
                                        //直接发放
                                        \app\custom\OrderCustom::deal_first_cashback($aid,$order['mid'],$back_price,$og,$v,0,'collage');
                                    }
                                }
                            }else{
                                if(getcustom('yx_cashback_time')){
                                    if($send_status && $back_price>0){
                                        //处理自定义第一次发放
                                        \app\custom\OrderCustom::deal_first_cashback($aid,$order['mid'],$back_price,$og,$v,1,'collage');
                                    }
                                }
                            }
                        }

                    }
                }

            }
        }
    }

    public static function deal_invitecashback($aid,$order,$oglist,$member){
        if(getcustom('yx_invite_cashback')){
            //邀请返现
            //查询上级是否有分销权限
            $parent = Db::name('member')
                ->alias('m')
                ->join('member_level ml','ml.id = m.levelid')
                ->where('m.id',$member['pid'])
                ->where('ml.can_agent','>',0)
                ->where('m.aid',$aid)
                ->field('m.id,m.levelid')
                ->find();
            if($parent){
                foreach($oglist as $og){

                    //查询商品
                    $product = Db::name('shop_product')
                        ->where('id',$og['proid'])
                        ->field('id,bid,cid')
                        ->find();
                    if($product){

                        //查询邀请返现设置
                        $iclist = Db::name('invite_cashback')
                            ->where('aid',$aid)
                            ->where('bid',0)
                            ->where('starttime','<',$order['paytime'])
                            ->where('endtime','>',$order['paytime'])
                            ->order('sort desc')
                            ->select()
                            ->toArray();
                        if($iclist){

                            //能发放奖励的列表
                            $new_iclist = [];
                            //查询是否有单独商品设置 若有则只发单独设置的返现设置
                            $alone   = false;

                            foreach($iclist as $v){
                                //返现设置是否存在
                                $v['invite_cashbak_data']  = $v['invite_cashbak_data'] ? json_decode($v['invite_cashbak_data'],true) : [];
                                if(empty($v['invite_cashbak_data'])){
                                    continue;
                                }

                                $gettj = explode(',',$v['gettj']);
                                if(!in_array('-1',$gettj) && !in_array($parent['levelid'],$gettj)){ //不是所有人
                                    continue;
                                }

                                if($v['fwtype']>=3){
                                    //其他类型不适应
                                    continue;
                                }

                                //指定商品:若指定商品，则不走所有商品及指定类目设置
                                if($v['fwtype']==2){
                                    $productids = explode(',',$v['productids']);
                                    if(!in_array($product['id'],$productids)){
                                        continue;
                                    }
                                    $alone = true;

                                    //如果需上级购买商品
                                    if($v['needbuy'] == 1){
                                        //查询上级是否买过此商品
                                        $ogoods = Db::name('shop_order_goods')
                                            ->alias('og')
                                            ->join('shop_order o','o.id=og.orderid')
                                            ->where('og.proid',$og['proid'])
                                            ->where('o.mid',$parent['id'])
                                            ->where('o.status','in','1,2,3')
                                            ->where('o.aid',$aid)
                                            ->field('og.id')
                                            //->order('o.status desc')
                                            ->find();
                                        if(!$ogoods){
                                            continue;
                                        }
                                    }

                                }else{
                                    //若指定商品，则不走所有商品及指定类目设置
                                    if($alone){
                                        continue;
                                    }

                                    if($v['fwtype']==1){//指定类目可用
                                        $categoryids = explode(',',$v['categoryids']);
                                        $cids  = explode(',',$product['cid']);
                                        $clist = Db::name('shop_category')->where('pid','in',$categoryids)->select()->toArray();
                                        foreach($clist as $vc){
                                            $categoryids[] = $vc['id'];
                                            $cate2 = Db::name('shop_category')->where('pid',$vc['id'])->find();
                                            $categoryids[] = $cate2['id'];
                                        }
                                        if(!array_intersect($cids,$categoryids)){
                                            continue;
                                        }
                                    }

                                    //如果需上级购买商品
                                    if($v['needbuy'] == 1){
                                        $where = [];
                                        $where[] = ['o.mid','=',$parent['id']];
                                        $where[] = ['o.status','in','1,2,3'];

                                        if($v['fwtype']==1){
                                            $whereCid = [];
                                            foreach($categoryids as $cid){
                                                $whereCid[] = "find_in_set({$cid},p.cid)";
                                            }
                                            $where[] = Db::raw(implode(' or ',$whereCid));
                                        }

                                        $where[] = ['o.aid','=',$aid];
                                        //查询上级是否买过商品
                                        $ogoods = Db::name('shop_order_goods')
                                            ->alias('og')
                                            ->join('shop_order o','o.id=og.orderid')
                                            ->join('shop_product p','p.id=og.proid')
                                            ->where($where)
                                            ->field('og.id')
                                            //->order('o.status desc')
                                            ->find();
                                        if(!$ogoods){
                                            continue;
                                        }
                                    }
                                }

                                //是否开启复购：若没开启，则每个邀请人一种商品只能发一次，开启则无邀请人数限制
                                if(!$v['isagain']){
                                    //查询此用户此商品是否已给上级记录过，记录过则不在发放
                                    $count = Db::name('member_invite_cashback_log')
                                        ->where('order_mid',$member['id'])
                                        ->where('mid',$parent['id'])
                                        ->where('cashback_id',$v['id']);
                                    if($v['fwtype']==2){
                                        $count = $count->where('proid',$og['proid']);
                                    }
                                    $count = $count
                                        ->where('status','>=',0)
                                        ->count();
                                    if($count){
                                        continue;
                                    }
                                }

                                //查询上级已返现过的次数
                                $pnum = Db::name('member_invite_cashback_log')
                                    ->where('mid',$parent['id']);
                                if($v['fwtype']==2){
                                    $pnum = $pnum->where('proid',$og['proid']);
                                }
                                $pnum = $pnum
                                    ->where('cashback_id',$v['id'])
                                    ->count();
                                $v['pnum'] = 0 + $pnum;

                                //查询设置的推N返一次数
                                $v['icnum'] = count($v['invite_cashbak_data']);

                                //若没有开启循环，则只按顺序发一次
                                if(!$v['iscycle'] && $v['pnum']>=$v['icnum']){
                                    continue;
                                }

                                //如果开启循环，且开启了循环次数限制，则需要查看循环几次后固定发奖设置
                                if($v['iscycle'] && $v['cyclenum']>0){
                                    //若固定发奖未设置则跳过发放
                                    if($v['cyclemoney'] <=0 && $v['cyclescore']<=0 && $v['cyclecommission']<=0 && $v['cyclemoney2'] <=0 && $v['cyclescore2']<=0 && $v['cyclecommission2']<=0){
                                        continue;
                                    }
                                }

                                array_push($new_iclist,$v);
                            }
                            unset($v);

                            //如果可以发放
                            if($new_iclist){
                                foreach($new_iclist as $v){
                                    //若有单独设置则只发单独设置的返现设置
                                    if($alone){
                                        if($v['fwtype']==2){
                                            //返现金额
                                            $back_price = $og['real_totalprice'];
                                            if(getcustom('money_dec')){
                                                //如果是余额抵扣，则要加上余额部分
                                                if($og['dec_money'] && $og['dec_money'] >0){
                                                    $back_price = $og['real_totalprice']+$og['dec_money'];
                                                }
                                            }
                                            if($back_price>0){
                                                //发放返回
                                                $mid_order_gid = $ogoods && $ogoods['id']?$ogoods['id']:0;
                                                self::deal_sendback($aid,$order,$og,$parent,$v,$back_price,$mid_order_gid);
                                            }
                                        }
                                    }else{
                                        //返现金额
                                        $back_price = $og['real_totalprice'];
                                        if(getcustom('money_dec')){
                                            //如果是余额抵扣，则要加上余额部分
                                            if($og['dec_money'] && $og['dec_money'] >0){
                                                $back_price = $og['real_totalprice']+$og['dec_money'];
                                            }
                                        }
                                        if($back_price>0){
                                            //发放返回
                                            $mid_order_gid = $ogoods && $ogoods['id']?$ogoods['id']:0;
                                            self::deal_sendback($aid,$order,$og,$parent,$v,$back_price,$mid_order_gid);
                                        }
                                    }
                                }
                                unset($v);
                            }
                        }
                        
                    }
                }
            }
        }
    }

    public static function deal_sendback($aid,$order,$og,$parent,$set,$back_price,$mid_order_gid=0){
        if(getcustom('yx_invite_cashback')){

            //固定余额返现
            $money       = 0;
            //百分比余额返现
            $money2      = 0;
            //固定积分返现
            $score       = 0;
            //百分比积分返现
            $score2      = 0;
            //固定佣金返现
            $commission  = 0;
            //百分比佣金返现
            $commission2 = 0;

            if(getcustom('yx_invite_cashback_ordertj')){
                //判断是否是付款后就发放
                if($set['ordertj'] && $set['ordertj'] == 1){
                    //如果开启循环，且开启了循环次数限制
                    if($set['iscycle'] && $set['cyclenum']>0){
                        //查询已循环的次数
                        $num = floor($set['pnum'] / $set['icnum']);
                        //若循环次数超出，则需要按照循环次数后固定发奖设置
                        if($num>=$set['cyclenum']){
                            //固定余额返现
                            $money       = $set['cyclemoney'];
                            //百分比
                            $money2      = $set['cyclemoney2']*$back_price/100/$og['num'];
                            //固定积分返现
                            $score       = $set['cyclescore'];
                            //百分比
                            $score2      = $set['cyclescore2']*$back_price/100/$og['num'];
                            //固定佣金返现
                            $commission  = $set['cyclecommission'];
                            //百分比
                            $commission2 = $set['cyclecommission2']*$back_price/100/$og['num'];
                        }else{
                            //查询余数 = 上级已返现过的次数%设置的推N返一次数
                            $ynum = $set['pnum'] % $set['icnum'];
                            foreach($set['invite_cashbak_data'] as $ik=>$iv){
                                if($ik == $ynum){
                                    //固定余额返现
                                    $money       = $iv['money'];
                                    //百分比余额返现
                                    $money2      = $iv['money2']*$back_price/100/$og['num'];
                                    //固定积分返现
                                    $score       = $iv['score'];
                                    //百分比积分返现
                                    $score2      = $iv['score2']*$back_price/100/$og['num'];
                                    //固定佣金返现
                                    $commission  = $iv['commission'];
                                    //百分比佣金返现
                                    $commission2 = $iv['commission2']*$back_price/100/$og['num'];
                                }
                            }
                            unset($ik);
                            unset($iv);
                        }
                    }else{
                        //查询余数 = 上级已返现过的次数%设置的推N返一次数
                        $ynum = $set['pnum'] % $set['icnum'];
                        foreach($set['invite_cashbak_data'] as $ik=>$iv){
                            if($ik == $ynum){
                                //固定余额返现
                                $money       = $iv['money'];
                                //百分比余额返现
                                $money2      = $iv['money2']*$back_price/100/$og['num'];
                                //固定积分返现
                                $score       = $iv['score'];
                                //百分比积分返现
                                $score2      = $iv['score2']*$back_price/100/$og['num'];
                                //固定佣金返现
                                $commission  = $iv['commission'];
                                //百分比佣金返现
                                $commission2 = $iv['commission2']*$back_price/100/$og['num'];
                            }
                        }
                        unset($ik);
                        unset($iv);
                    }
                }
            }

            //总余额
            $allmoney = $money+$money2;
            $allmoney = round($allmoney,2);
            //总积分
            $allscore = $score+$score2;
            $allscore = intval($allscore);
            //总佣金
            $allcommission = $commission+$commission2;
            $allcommission = round($allcommission,2);

            //添加返回记录
            $log = [];
            $log['aid'] = $aid;
            $log['mid'] = $parent['id'];//返回者

            $status = 0;
            if(getcustom('yx_invite_cashback_ordertj')){
                //判断是否是付款后就发放
                if($set['ordertj'] && $set['ordertj'] == 1){
                    $log['mid_order_gid'] = $mid_order_gid;
                    $status = 1;
                }
            }
            //商品信息
            $log['proid']        = $og['proid'];
            $log['num']          = $og['num'];
            $log['back_price']   = $back_price;

            $log['order_id']     = $order['id'];//订单id
            $log['order_gid']    = $og['id'];//订单商品id
            $log['order_mid']    = $order['mid'];//订单用户id
            $log['cashback_id']  = $set['id'];//邀请返现设置id
            $log['productids']   = !empty($set['productids'])?$set['productids']:'';
            $log['categoryids']  = !empty($set['categoryids'])?$set['categoryids']:'';

            $log['money']        = $money;
            $log['money2']       = $money2;
            $log['allmoney']     = $allmoney;
            $log['score']        = $score;
            $log['score2']       = $score2;
            $log['allscore']     = $allscore;
            $log['commission']   = $commission;
            $log['commission2']  = $commission2;
            $log['allcommission']= $allcommission;
            $log['status']       = $status;
            $log['create_time']  = time();
            $log['update_time']  = time();
            $insert = Db::name('member_invite_cashback_log')->insert($log);
            if(getcustom('yx_invite_cashback_ordertj')){
                //判断是否是付款后就发放
                if($set['ordertj'] && $set['ordertj'] == 1){
                    if($insert){
                        $remark = '商品'.$og['name'].'邀请返还';
                        if($allmoney>0 ){
                            \app\common\Member::addmoney($aid,$parent['id'],$allmoney,$remark);
                        }
                        if($allscore){
                            \app\common\Member::addscore($aid,$parent['id'],$allscore,$remark);
                        }
                        if($allcommission>0){
                            \app\common\Member::addcommission($aid,$parent['id'],$order['mid'],$allcommission,$remark);
                        }
                    }
                }
            }

        }
    }
    public static function deal_ictips($aid,$mid,$type=0,$prodoucts=[]){
        
        if(getcustom('yx_invite_cashback')){

            if($type == 1){
                $payorder = $prodoucts;
                if($payorder['type'] == 'shop'){
                    $proids = Db::name('shop_order_goods')->where('orderid',$payorder['orderid'])->where('aid',aid)->column('proid');
                }else{
                    $proids = Db::name('shop_order_goods')->where('ordernum', 'like',  $payorder['ordernum'] . '_%' )->where('aid',aid)->column('proid');
                }
                if($proids){
                    $where   = [];
                    $where[] = ['id','in',$proids];
                    $where[] = ['aid','=',$aid];
                    $nowtime   = time();
                    $nowhm     = date('H:i');
                    $where[] = Db::raw("`status`=1 or (`status`=2 and unix_timestamp(start_time)<=$nowtime and unix_timestamp(end_time)>=$nowtime) or (`status`=3 and ((start_hours<end_hours and start_hours<='$nowhm' and end_hours>='$nowhm') or (start_hours>=end_hours and (start_hours<='$nowhm' or end_hours>='$nowhm'))) )");
                    $where[] = ['ischecked','=',1];
                    $prodoucts = Db::name('shop_product')->where($where)->field('id,aid,bid,cid,pic,name')->select()->toArray();
                }else{
                    $prodoucts = [];
                }
            }

            $member = Db::name('member')
                ->alias('m')
                ->join('member_level ml','ml.id = m.levelid')
                ->where('m.id',$mid)
                ->where('ml.can_agent','>',0)
                ->where('m.aid',$aid)
                ->field('m.id,m.levelid')
                ->find();

            $data = [];
            $data['ictips']  = '';
            $data['proid']   = '';
            $data['propic']  = '';
            $data['proname'] = '';
            if($prodoucts){
                //查询邀请返现
                $iclist = Db::name('invite_cashback')
                    ->where('aid',$aid)
                    ->where('bid',0)
                    ->where('starttime','<',time())
                    ->where('endtime','>',time())
                    ->order('sort desc')
                    ->select()
                    ->toArray();

                if($iclist){
                    //能发放奖励的列表
                    $new_iclist = [];
                    //查询是否有单独商品设置 若有则只发单独设置的返现设置
                    $alone   = false;
                    foreach($prodoucts as $product){
                        if($data['ictips']){
                            break;
                        }
                        foreach($iclist as $v){

                            //返现设置是否存在
                            $v['invite_cashbak_data']  = $v['invite_cashbak_data'] ? json_decode($v['invite_cashbak_data'],true) : [];
                            if(empty($v['invite_cashbak_data'])){
                                continue;
                            }

                            $gettj = explode(',',$v['gettj']);
                            if(!in_array('-1',$gettj) && !in_array($member['levelid'],$gettj)){ //不是所有人
                                continue;
                            }

                            if($v['fwtype']>=3){
                                //其他类型不适应
                                continue;
                            }

                            if($v['fwtype']==2){//指定商品可用
                                $productids = explode(',',$v['productids']);
                                if(!in_array($product['id'],$productids)){
                                    continue;
                                }
                                $alone = true;
                            }else if($v['fwtype']==1){//指定类目可用
                                $categoryids = explode(',',$v['categoryids']);
                                $cids  = explode(',',$product['cid']);
                                $clist = Db::name('shop_category')->where('pid','in',$categoryids)->select()->toArray();
                                foreach($clist as $vc){
                                    $categoryids[] = $vc['id'];
                                    $cate2 = Db::name('shop_category')->where('pid',$vc['id'])->find();
                                    $categoryids[] = $cate2['id'];
                                }
                                if(!array_intersect($cids,$categoryids)){
                                    continue;
                                }
                            }
                            array_push($new_iclist,$v);
                        }
                        //如果可以发放
                        if($new_iclist){
                            foreach($new_iclist as $v){
                                //若有单独设置则只发单独设置的返现设置
                                if($alone){
                                    if($v['fwtype']==2){
                                        //计算N数值
                                        $icnum = count($v['invite_cashbak_data']);
                                        if($icnum>0){
                                            $data['ictips']  = $type?'推荐'.$icnum.'个人消费全返，点击分享好友':'推荐'.$icnum.'个人消费全返';
                                            $data['proid']   = $product['id'];
                                            $data['propic']  = $product['pic'];
                                            $data['proname'] = $product['name'];
                                        }
                                    }
                                }else{
                                    //计算N数值
                                    $icnum = count($v['invite_cashbak_data']);
                                    if($icnum>0){
                                        $data['ictips']  = $type?'推荐'.$icnum.'个人消费全返，点击分享好友':'推荐'.$icnum.'个人消费全返';
                                        $data['proid']   = $product['id'];
                                        $data['propic']  = $product['pic'];
                                        $data['proname'] = $product['name'];
                                    }
                                }
                            }
                            unset($v);
                        }
                    }
                    
                }
            }
            return $data;
        }
    }

    public static function deal_invitecashback2($aid,$order,$oglist,$member){
        if(getcustom('yx_invite_cashback')){
            //处理邀请邀请返现
            foreach($oglist as $og){

                //查询商品
                $product = Db::name('shop_product')
                    ->where('id',$og['proid'])
                    ->field('id,bid,cid')
                    ->find();
                if(!$product){
                    Db::name('member_invite_cashback_log')->where('proid',$og['proid'])->where('status',0)->update(['status'=>-1,'update_time'=>time(),'cancel_time'=>time(),'reason'=>'商品不存在']);
                    continue;
                }

                //查询记录是否存在
                $loglist = Db::name('member_invite_cashback_log')
                    ->where('order_id',$order['id'])
                    ->where('proid',$og['proid'])
                    ->where('order_mid',$order['mid'])
                    ->where('status',0)
                    ->select()
                    ->toArray();
                if($loglist){

                    foreach($loglist as $lv){

                        //查询上级是否有分销权限
                        $parent = Db::name('member')
                            ->alias('m')
                            ->join('member_level ml','ml.id = m.levelid')
                            ->where('m.id',$lv['mid'])
                            ->where('ml.can_agent','>',0)
                            ->where('m.aid',$aid)
                            ->field('m.id,m.levelid')
                            ->find();
                        if(!$parent){
                            Db::name('member_invite_cashback_log')->where('id',$lv['id'])->where('status',0)->update(['status'=>-1,'update_time'=>time(),'cancel_time'=>time(),'reason'=>'上级不存在或无分销权限']);
                            continue;
                        }

                        //查询邀请返现
                        $set = Db::name('invite_cashback')
                            ->where('id',$lv['cashback_id'])
                            ->where('aid',$aid)
                            ->where('bid',0)
                            ->where('starttime','<',$order['paytime'])
                            ->where('endtime','>',$order['paytime'])
                            ->find();
                        if(!$set){
                            Db::name('member_invite_cashback_log')->where('id',$lv['id'])->where('status',0)->update(['status'=>-1,'update_time'=>time(),'cancel_time'=>time(),'reason'=>'邀请返现活动不存在或已结束']);
                            continue;
                        }

                        if(getcustom('yx_invite_cashback_ordertj')){
                            //判断是否是确认收货后发放,不是则不发放
                            if($set['ordertj'] || $set['ordertj'] == 1){
                                continue;
                            }
                        }

                        if($set['fwtype']==2){
                            $productids = explode(',',$set['productids']);
                            if(!in_array($product['id'],$productids)){
                                Db::name('member_invite_cashback_log')->where('id',$lv['id'])->where('status',0)->update(['status'=>-1,'update_time'=>time(),'cancel_time'=>time(),'reason'=>'邀请活动已失效']);
                                continue;
                            }

                            //如果需上级购买商品
                            if($set['needbuy'] == 1){
                                //再验证上级是否买过此商品
                                $ogoods = Db::name('shop_order_goods')
                                    ->alias('og')
                                    ->join('shop_order o','o.id=og.orderid')
                                    ->where('og.proid',$og['proid'])
                                    ->where('o.mid',$lv['mid'])
                                    ->where('o.status',3)
                                    ->where('o.aid',$aid)
                                    ->field('og.id')
                                    ->find();
                                if(!$ogoods){
                                    Db::name('member_invite_cashback_log')->where('id',$lv['id'])->where('status',0)->update(['status'=>-1,'update_time'=>time(),'cancel_time'=>time(),'reason'=>'上级购买此商品记录不存在或订单未完成']);
                                    continue;
                                }
                            }
                            $alone = true;
                        }else{
                            if($set['fwtype']==1){//指定类目可用
                                $categoryids = explode(',',$set['categoryids']);
                                $cids  = explode(',',$product['cid']);
                                $clist = Db::name('shop_category')->where('pid','in',$categoryids)->select()->toArray();
                                foreach($clist as $vc){
                                    $categoryids[] = $vc['id'];
                                    $cate2 = Db::name('shop_category')->where('pid',$vc['id'])->find();
                                    $categoryids[] = $cate2['id'];
                                }
                                if(!array_intersect($cids,$categoryids)){
                                    Db::name('member_invite_cashback_log')->where('id',$lv['id'])->where('status',0)->update(['status'=>-1,'update_time'=>time(),'cancel_time'=>time(),'reason'=>'邀请活动已失效']);
                                    continue;
                                }
                            }

                            //如果需上级购买商品
                            if($set['needbuy'] == 1){
                                $where = [];
                                $where[] = ['o.mid','=',$lv['mid']];
                                $where[] = ['o.status','=',3];

                                if($set['fwtype']==1){
                                    $whereCid = [];
                                    foreach($categoryids as $cid){
                                        $whereCid[] = "find_in_set({$cid},p.cid)";
                                    }
                                    $where[] = Db::raw(implode(' or ',$whereCid));
                                }

                                $where[] = ['o.aid','=',$aid];
                                //再验证上级是否买过商品
                                $ogoods = Db::name('shop_order_goods')
                                    ->alias('og')
                                    ->join('shop_order o','o.id=og.orderid')
                                    ->join('shop_product p','p.id=og.proid')
                                    ->where($where)
                                    ->field('og.id')
                                    ->find();
                                if(!$ogoods){
                                    Db::name('member_invite_cashback_log')->where('id',$lv['id'])->where('status',0)->update(['status'=>-1,'update_time'=>time(),'cancel_time'=>time(),'reason'=>'上级购买记录不存在或订单未完成']);
                                    continue;
                                }
                            }
                        } 

                        //返现设置数据是否存在
                        $set['invite_cashbak_data']  = $set['invite_cashbak_data'] ? json_decode($set['invite_cashbak_data'],true) : [];
                        if(empty($set['invite_cashbak_data'])){
                            Db::name('member_invite_cashback_log')->where('id',$lv['id'])->update(['status'=>-1,'update_time'=>time(),'cancel_time'=>time(),'reason'=>'邀请返现活动已失效']);
                            continue;
                        }

                        $gettj = explode(',',$set['gettj']);
                        if(!in_array('-1',$gettj) && !in_array($parent['levelid'],$gettj)){ //不是所有人
                            Db::name('member_invite_cashback_log')->where('id',$lv['id'])->update(['status'=>-1,'update_time'=>time(),'cancel_time'=>time(),'reason'=>'上级等级不符']);
                            continue;
                        }

                        if($set['fwtype']>=3){
                            //其他类型不适应
                            Db::name('member_invite_cashback_log')->where('id',$lv['id'])->update(['status'=>-1,'update_time'=>time(),'cancel_time'=>time(),'reason'=>'邀请返现类型错误']);
                            continue;
                        }

                        //是否开启复购，若没开启，则每个邀请人只能发一次，开启则无邀请人数限制
                        if(!$set['isagain']){
                            //查询此用户此商品是否已给上级记录过，记录过则不在发放
                            $count = Db::name('member_invite_cashback_log')
                                ->where('order_mid',$member['id'])
                                ->where('mid',$parent['id'])
                                ->where('cashback_id',$set['id']);
                            if($set['fwtype']==2){
                                 $count = $count->where('proid',$og['proid']);
                            }
                            $count = $count
                                ->where('status',1)
                                ->count();
                            if($count){
                                Db::name('member_invite_cashback_log')->where('id',$lv['id'])->update(['status'=>-1,'update_time'=>time(),'cancel_time'=>time(),'reason'=>'此邀请人此商品已给上级发放过返现']);
                                continue;
                            }
                        }

                        //查询上级已返现过的次数
                        $pnum = Db::name('member_invite_cashback_log')
                            ->where('mid',$parent['id']);
                        if($set['fwtype']==2){
                            $pnum = $pnum->where('proid',$og['proid']);
                        }
                        $pnum = $pnum
                            ->where('cashback_id',$set['id'])
                            ->where('status',1)
                            ->count();
                        $set['pnum'] = 0+$pnum;

                        //查询设置的推N返一次数
                        $set['icnum'] = count($set['invite_cashbak_data']);

                        //若没有开启循环，则只按顺序发一次
                        if(!$set['iscycle'] && $set['pnum']>=$set['icnum']){
                            Db::name('member_invite_cashback_log')->where('id',$lv['id'])->update(['status'=>-1,'update_time'=>time(),'cancel_time'=>time(),'reason'=>'此邀请返现活动上级奖励已全部发放完毕']);
                            continue;
                        }

                        //如果开启循环，且开启了循环次数限制，则需要查看循环几次后固定发奖设置
                        if($set['iscycle'] && $set['cyclenum']>0){
                            //若固定发奖未设置则跳过发放
                            if($set['cyclemoney'] <=0 && $set['cyclescore']<=0 && $set['cyclecommission']<=0 && $set['cyclemoney2'] <=0 && $set['cyclescore2']<=0 && $set['cyclecommission2']<=0){
                                Db::name('member_invite_cashback_log')->where('id',$lv['id'])->update(['status'=>-1,'update_time'=>time(),'cancel_time'=>time(),'reason'=>'循环次数已满']);
                                continue;
                            }
                        }

                        //返现金额
                        $back_price = $og['real_totalprice'];
                        if(getcustom('money_dec')){
                            //如果是余额抵扣，则要加上余额部分
                            if($og['dec_money'] && $og['dec_money'] >0){
                                $back_price = $og['real_totalprice']+$og['dec_money'];
                            }
                        }
                        if($back_price>0){
                            //发放返回
                            $mid_order_gid = $ogoods && $ogoods['id']?$ogoods['id']:0;
                            self::deal_sendback2($aid,$mid_order_gid,$lv['id'],$order,$og,$parent,$set,$back_price);
                        }else{
                            Db::name('member_invite_cashback_log')->where('id',$lv['id'])->update(['status'=>-1,'update_time'=>time(),'cancel_time'=>time(),'reason'=>'订单商品实际金额小于等于0']);
                            continue;
                        }
                    }
                }
            }
        }
    }
    public static function deal_sendback2($aid,$mid_order_gid,$logid,$order,$og,$parent,$set,$back_price){
        if(getcustom('yx_invite_cashback')){

            //固定余额返现
            $money       = 0;
            //百分比余额返现
            $money2      = 0;
            //固定积分返现
            $score       = 0;
            //百分比积分返现
            $score2      = 0;
            //固定佣金返现
            $commission  = 0;
            //百分比佣金返现
            $commission2 = 0;
            
            //如果开启循环，且开启了循环次数限制
            if($set['iscycle'] && $set['cyclenum']>0){
                //查询已循环的次数
                $num = floor($set['pnum'] / $set['icnum']);
                //若循环次数超出，则需要按照循环次数后固定发奖设置
                if($num>=$set['cyclenum']){
                    //固定余额返现
                    $money       = $set['cyclemoney'];
                    //百分比
                    $money2      = $set['cyclemoney2']*$back_price/100/$og['num'];
                    //固定积分返现
                    $score       = $set['cyclescore'];
                    //百分比
                    $score2      = $set['cyclescore2']*$back_price/100/$og['num'];
                    //固定佣金返现
                    $commission  = $set['cyclecommission'];
                    //百分比
                    $commission2 = $set['cyclecommission2']*$back_price/100/$og['num'];
                }else{
                    //查询余数 = 上级已返现过的次数%设置的推N返一次数
                    $ynum = $set['pnum'] % $set['icnum'];
                    foreach($set['invite_cashbak_data'] as $ik=>$iv){
                        if($ik == $ynum){
                            //固定余额返现
                            $money       = $iv['money'];
                            //百分比余额返现
                            $money2      = $iv['money2']*$back_price/100/$og['num'];
                            //固定积分返现
                            $score       = $iv['score'];
                            //百分比积分返现
                            $score2      = $iv['score2']*$back_price/100/$og['num'];
                            //固定佣金返现
                            $commission  = $iv['commission'];
                            //百分比佣金返现
                            $commission2 = $iv['commission2']*$back_price/100/$og['num'];
                        }
                    }
                    unset($ik);
                    unset($iv);
                }
            }else{
                //查询余数 = 上级已返现过的次数%设置的推N返一次数
                $ynum = $set['pnum'] % $set['icnum'];
                foreach($set['invite_cashbak_data'] as $ik=>$iv){
                    if($ik == $ynum){
                        //固定余额返现
                        $money       = $iv['money'];
                        //百分比余额返现
                        $money2      = $iv['money2']*$back_price/100/$og['num'];
                        //固定积分返现
                        $score       = $iv['score'];
                        //百分比积分返现
                        $score2      = $iv['score2']*$back_price/100/$og['num'];
                        //固定佣金返现
                        $commission  = $iv['commission'];
                        //百分比佣金返现
                        $commission2 = $iv['commission2']*$back_price/100/$og['num'];
                    }
                }
                unset($ik);
                unset($iv);
            }

            //总余额
            $allmoney = $money+$money2;
            $allmoney = round($allmoney,2);
            //总积分
            $allscore = $score+$score2;
            $allscore = intval($allscore);
            //总佣金
            $allcommission = $commission+$commission2;
            $allcommission = round($allcommission,2);

            //添加返回记录
            $log = [];
            $log['mid_order_gid'] = $mid_order_gid;//返回者购买订单商品id

            //商品信息
            $log['num']          = $og['num'];
            $log['back_price']   = $back_price;
            //$log['cashback_id']  = $set['id'];//邀请返现设置id

            $log['money']        = $money;
            $log['money2']       = $money2;
            $log['allmoney']     = $allmoney;
            $log['score']        = $score;
            $log['score2']       = $score2;
            $log['allscore']     = $allscore;
            $log['commission']   = $commission;
            $log['commission2']  = $commission2;
            $log['allcommission']= $allcommission;
            $log['status']       = 1;
            $log['update_time']  = time();
            $insert = Db::name('member_invite_cashback_log')->where('status',0)->where('id',$logid)->update($log);

            if($insert){
                $remark = '商品'.$og['name'].'邀请返还';
                if($allmoney>0 ){
                    \app\common\Member::addmoney($aid,$parent['id'],$allmoney,$remark);
                }
                if($allscore){
                    \app\common\Member::addscore($aid,$parent['id'],$allscore,$remark);
                }
                if($allcommission>0){
                    \app\common\Member::addcommission($aid,$parent['id'],$order['mid'],$allcommission,$remark);
                }
            }
        }
    }

    public static function count_sendback($aid,$log){
        if(getcustom('yx_invite_cashback')){
            //计算未发放的记录奖励
            $status = $log['status'];

            //固定余额返现
            $money       = 0;
            //百分比余额返现
            $money2      = 0;
            //固定积分返现
            $score       = 0;
            //百分比积分返现
            $score2      = 0;
            //固定佣金返现
            $commission  = 0;
            //百分比佣金返现
            $commission2 = 0;

            $order = Db::name('shop_order')->where('id',$log['order_id'])->where('aid',$aid)->field('paytime')->find();
            if($order){
                //查询邀请返现
                $set = Db::name('invite_cashback')
                    ->where('id',$log['cashback_id'])
                    ->where('aid',$aid)
                    ->where('bid',0)
                    ->where('starttime','<',$order['paytime'])
                    ->where('endtime','>',$order['paytime'])
                    ->find();
                if($set){

                    $set['invite_cashbak_data'] = $set['invite_cashbak_data']?json_decode($set['invite_cashbak_data'],true):[];
                    if(!empty($set['invite_cashbak_data'])){
                        //查询上级已返现过的次数
                        $pnum1 = Db::name('member_invite_cashback_log')
                            ->where('id','<',$log['id'])
                            ->where('mid',$log['mid']);
                        if($set['fwtype']==2){
                            $pnum1 = $pnum1->where('proid',$log['proid']);
                        }
                        $pnum1 = $pnum1
                            ->where('cashback_id',$set['id'])
                            ->where('status',0)
                            ->count();
                        $pnum1 = 0+$pnum1;

                        $pnum2 = Db::name('member_invite_cashback_log')
                            ->where('mid',$log['mid']);
                        if($set['fwtype']==2){
                            $pnum2 = $pnum2->where('proid',$log['proid']);
                        }
                        $pnum2 = $pnum2
                            ->where('cashback_id',$set['id'])
                            ->where('status',1)
                            ->count();
                        $pnum2 = 0+$pnum2;

                        $set['pnum'] =  $pnum1+$pnum2;
                        //查询设置的推N返一次数
                        $set['icnum'] = count($set['invite_cashbak_data']);

                        //若没有开启循环，则只按顺序发一次
                        if(!$set['iscycle'] && $set['pnum']>=$set['icnum']){
                            Db::name('member_invite_cashback_log')->where('id',$log['id'])->update(['status'=>-1,'cancel_time'=>time(),'reason'=>'此邀请返现活动上级奖励已全部发放完毕']);
                            $status = -1;
                        }else{
                            //如果开启循环，且开启了循环次数限制，则需要查看循环几次后固定发奖设置
                            if($set['iscycle'] && $set['cyclenum']>0){
                                //若固定发奖未设置则跳过发放
                                if($set['cyclemoney'] <=0 && $set['cyclescore']<=0 && $set['cyclecommission']<=0 && $set['cyclemoney2'] <=0 && $set['cyclescore2']<=0 && $set['cyclecommission2']<=0){
                                    Db::name('member_invite_cashback_log')->where('id',$log['id'])->update(['status'=>-1,'update_time'=>time(),'cancel_time'=>time(),'reason'=>'循环次数已满']);
                                    $status = -1;
                                }else{
                                    //查询已循环的次数
                                    $num = floor($set['pnum'] / $set['icnum']);
                                    //若循环次数超出，则需要按照循环次数后固定发奖设置
                                    if($num>=$set['cyclenum']){
                                        //固定余额返现
                                        $money       = $set['cyclemoney'];
                                        $money2      = $set['cyclemoney2']*$log['back_price']/100/$log['num'];
                                        //固定积分返现
                                        $score       = $set['cyclescore'];
                                        $score2      = $set['cyclescore2']*$log['back_price']/100/$log['num'];
                                        //固定佣金返现
                                        $commission  = $set['cyclecommission'];
                                        $commission2 = $set['cyclecommission2']*$log['back_price']/100/$log['num'];
                                    }else{
                                        //查询余数 = 上级已返现过的次数%设置的推N返一次数
                                        $ynum = $set['pnum'] % $set['icnum'];
                                        foreach($set['invite_cashbak_data'] as $ik=>$iv){
                                            if($ik == $ynum){
                                                //固定余额返现
                                                $money       = $iv['money'];
                                                //百分比余额返现
                                                $money2      = $iv['money2']*$log['back_price']/100/$log['num'];
                                                //固定积分返现
                                                $score       = $iv['score'];
                                                //百分比积分返现
                                                $score2      = $iv['score2']*$log['back_price']/100/$log['num'];
                                                //固定佣金返现
                                                $commission  = $iv['commission'];
                                                //百分比佣金返现
                                                $commission2 = $iv['commission2']*$log['back_price']/100/$log['num'];
                                            }
                                        }
                                        unset($ik);
                                        unset($iv);
                                    }
                                }
                            }else{
                                //查询余数 = 上级已返现过的次数%设置的推N返一次数
                                $ynum = $set['pnum'] % $set['icnum'];
                                foreach($set['invite_cashbak_data'] as $ik=>$iv){
                                    if($ik == $ynum){
                                        //固定余额返现
                                        $money       = $iv['money'];
                                        //百分比余额返现
                                        $money2      = $iv['money2']*$log['back_price']/100/$log['num'];
                                        //固定积分返现
                                        $score       = $iv['score'];
                                        //百分比积分返现
                                        $score2      = $iv['score2']*$log['back_price']/100/$log['num'];
                                        //固定佣金返现
                                        $commission  = $iv['commission'];
                                        //百分比佣金返现
                                        $commission2 = $iv['commission2']*$log['back_price']/100/$log['num'];
                                    }
                                }
                                unset($ik);
                                unset($iv);
                            }

                            //总余额
                            $allmoney = $money+$money2;
                            $allmoney = round($allmoney,2);
                            //总积分
                            $allscore = $score+$score2;
                            $allscore = intval($allscore);
                            //总佣金
                            $allcommission = $commission+$commission2;
                            $allcommission = round($allcommission,2);
                        }

                    }else{
                        Db::name('member_invite_cashback_log')->where('id',$log['id'])->update(['status'=>-1,'cancel_time'=>time(),'reason'=>'邀请返现活动已失效']);
                        $status = -1;
                    }
                    
                }else{
                    Db::name('member_invite_cashback_log')->where('id',$log['id'])->update(['status'=>-1,'cancel_time'=>time(),'reason'=>'邀请返现活动不存在或已结束']);
                    $status = -1;
                }
            }else{
                Db::name('member_invite_cashback_log')->where('id',$log['id'])->update(['status'=>-1,'cancel_time'=>time(),'reason'=>'下级订单不存在']);
                $status = -1;
            }

            $data = [];
            //商品信息
            $data['money']        = $money;
            $data['money2']       = $money2;
            $data['allmoney']     = $allmoney;
            $data['score']        = $score;
            $data['score2']       = $score2;
            $data['allscore']     = $allscore;
            $data['commission']   = $commission;
            $data['commission2']  = $commission2;
            $data['allcommission']= $allcommission;
            $data['allcommission']= $allcommission;
            $data['status']       = $status;

            return $data;
        }
    }

    public function cancel_invitecashbacklog($aid,$order,$reason=''){
        if(getcustom('yx_invite_cashback')){
            //订单取消返回
            $logs = Db::name('member_invite_cashback_log')
                ->where('order_id',$order['id'])
                ->where('order_mid',$order['mid'])
                ->where('aid',$aid)
                ->where('status',0)
                ->update(['status'=>-1,'cancel_time'=>time(),'reason'=>$reason]);
        }
    }
    /**
     * 所有参与活动的用户平均发放返现记录
     * aid 商家id
     * mid 会员id
     * cashback 购物返现活动
     * og 商品
     * back_price_total 返现数量
     */   
     
     public static function cashbackMemerDoLog($aid,$mid,$cashback,$og,$back_price_total){

        $cashback_member = [];                                            
        $cashback_member['aid'] = $aid;
        $cashback_member['mid'] = $mid;
        $cashback_member['cashback_id'] = $cashback['id'];
        $cashback_member['pro_id'] = $og['proid'];
        if($cashback['back_type'] == 1 ){
            $cashback_member['cashback_money'] = $back_price_total;
        }else if($cashback['back_type'] == 2 ){
            $cashback_member['commission'] = $back_price_total;
        }else if($cashback['back_type'] == 3 ){
            $cashback_member['score'] = $back_price_total;
        }
        
        $cashback_member['back_type']          = $cashback['back_type'];
        $cashback_member['create_time'] = time();
        $insert = Db::name('cashback_member_log')->insert($cashback_member);
        return $insert;
    }
}